<?php
namespace app\admin\controller;

class Group extends Base{
    //
    protected function initialize() {
        parent::initialize();
        $this->model = 'Group';
    }
    //
    protected function _before_index(){
        $thead = [
            'id' => 'GID',
            'title' =>'群组名称',
            'status' =>'可用状态',
            'rules' =>'拥有权限',
        ];
        $this->assign('thead', $thead);
    }
    //
    protected function _filter($map){
        return $map;
    }
    //
    protected function _after_list($list){
        $rule = model('Rule');
        foreach($list as $key => $row){
            $ruleArr = $rule->whereIn('id', $row['rules'])->column('title');
            $list[$key]['rules'] = implode(',', $ruleArr);
            $list[$key]['status'] = $row['status'] == '1' ? '可用' : '禁用';
        }
        return $list;
    }
    //
    protected function _before_add(){
        $module = model('Module');
        $rule = model('Rule');
        $rArr = [];
        $fArr = $module->where('fid', '=', 0)->field('id,title')->select()->toArray();
        foreach($fArr as $row1){
            $sArr = $module->where('fid', '=', $row1['id'])->field('id,title')->select()->toArray();
            foreach($sArr as $row){
                $rArr[$row1['title'].' * '.$row['title']] = $rule->where('module_id', '=', $row['id'])->field('id,title')->select()->toArray();
            }
        }
        $this->assign('rArr', $rArr);
    }
    //
    protected function _before_insert($data){
        $data['rules'] = $data['rules'] ?? [];
        $data['rules'] = implode(',', $data['rules']);
        return $data;
    }
    //
    protected function _after_add($data, $id){
        $this->log(['pk' => 'id', 'value' => $id], $data);
    }
    //
    protected function _before_edit(){
        $this->_before_add();
    }
    //
    protected function _filter_edit($list){
        $list['rules'] = explode(',', $list['rules']);
        return $list;
    }
    //
    protected function _before_save($data){
        return $this->_before_insert($data);
    }
    //
    protected function _after_edit($data){
        $this->log(['pk' => 'id', 'value' => $data['id']], $data);
    }
    //
    protected function _filter_del(){
        return [1];
    }
    //
    protected function _after_del($rows){
        $logs = [];
        foreach($rows as $row){
            $logs[] = ['pk' => 'id', 'value' => $row['id'], 'row' => $row];
        }
        $this->logAll($logs);
    }
}